package ar.edu.unq.sandsoft.constructors;

import java.io.IOException;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

import ar.edu.unq.sandsoft.exceptions.CouldnFindAttribute;
import ar.edu.unq.sandsoft.utils.SandFile;

public class AbstractSandReader {
    protected static final String NAME = "name";

    private SandFile file;

    private Document associatedDocument;

    protected AbstractSandReader(SandFile file) {
        this.file = file;
    }

    /**
     * Mandatory method, take a first peek to the document;
     */
    public void glance() throws SAXException, IOException, ParserConfigurationException {
        try {
            this.setAssociatedDocument(DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file));
            this.getAssociatedDocument().getDocumentElement().normalize();
        } catch (SAXException e) {
            throw e;
        } catch (IOException e) {
            throw e;
        } catch (ParserConfigurationException e) {
            throw e;
        }
    }

    // setters&getters
    public void setFile(SandFile file) {
        this.file = file;
    }

    public SandFile getFile() {
        return file;
    }

    public void setAssociatedDocument(Document associatedDocument) {
        this.associatedDocument = associatedDocument;
    }

    public Document getAssociatedDocument() {
        return associatedDocument;
    }

    /**
     * Para generar un reporte de errores, wrapeamos el get node value!
     */
    protected String findAttribute(String name, Node item) throws CouldnFindAttribute {
        String value = null;
        try {
            value = item.getAttributes().getNamedItem(name).getNodeValue();
        } catch (Exception e) {
            throw new CouldnFindAttribute(name, file.getName());
        }
        return value;
    
    }
}
